<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title th:text="'信息' + (${type == 0 ? '收集' : '发布'}) + '端'">信息发布端</title>
    <link rel="shortcut icon" type="image/x-icon" th:href="@{/static/img/favicon.ico}"/>
    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/bootstrap/css/bootstrap.min.css}">
    <link rel="stylesheet" type="text/css"
          th:href="@{/plugins/font-awesome/css/font-awesome.min.css}">
    <script th:src="@{/js/jquery.min.js}" crossorigin="anonymous"></script>
    <script th:src="@{/plugins/bootstrap/js/bootstrap.min.js}" crossorigin="anonymous"></script>

    <style>
        #whole {
            position: fixed;
            left: 0px;
            right: 0px;
            top: 0px;
            bottom: 0px;
            background: #f5f5f5;

            display: flex;
            justify-content: space-between;
        }

        #right {
            height: 100%;
            flex-grow: 3;
            display: flex;
            flex-direction: column;
        }

        nav {
            width: 200px;
            height: 100%;
            display: flex;
            flex-direction: column;
        }

        nav .title {
            display: block;
            height: 50px;
            line-height: 50px;
            font-size: 20px;
            text-align: center;
            background: #367fa9;
            color: #fff;
        }

        nav #navs {
            flex-grow: 3;
            background: #2f4050;
        }

        header {
            width: 100%;
            min-height: 50px;
            background: #3c8dbc;
            display: flex;
            flex-direction: row-reverse;
            justify-content: space-between;
            color: #fff;
            z-index: 1000;
        }

        header #status-control {
            display: flex;
            justify-content: flex-end;
            align-items: center;
            position: relative;
            cursor: pointer;
            width: 130px;
        }

        #status-control span {
            padding: 0px 10px 0px 15px;
            font-weight: 600;
        }
        #status-control .avatar {
            padding: 1px;
        }

        #my-dropdown-menu {
            position: absolute;
            top: 48px;
            right: 0px;
        }

        .avatar {
            width: 35px;
            height: 35px;
        }

        main {
            flex-grow: 3;
            padding: 10px;
        }

        footer {
            width: 100%;
            padding: 10px 20px;
            border-top: 1px solid #e7eaec;
            background: #fff;
        }

        #navs .nav-item-box {
            padding-left: 14px;
        }

        #navs .nav-item {
            display: block;
            width: 100%;
            font-weight: 600;
            color: #a7b1c2;
            height: 46px;
            line-height: 46px;
            font-size: 15px;
            font-weight: 600;
        }

        #navs a {
            color: #a7b1c2;
            text-decoration: none;
        }

        #tabs {
            width: 100%;
            height: 39px;
            background: #fff;
        }

        #tabs div {
            display: inline-block;
            margin: 0px;
            padding: 0px 10px;
            height: 100%;
            line-height: 39px;
            background: red;
        }

        .nav-active {
            color: #1890ff !important;
        }

        #navs .hidden {
            display: none;
        }

        #navs i {
            width: 17px;
            text-align: center;
        }

        main > iframe {
            border: none;
            background: #fff;
        }

        .messageCount {
            margin: 0px 15px 5px;
            padding: 0px 5px;
            background: #fa5151;
            color: #fff;

        }

        #sex-radio-box {
            display: flex;
            justify-content: flex-start;
        }

        #sex-radio-box > div:nth-last-child(1) {
            margin-left: 20px;
        }

        #avatar-img {
            width: 90px;
            height: 90px;
            display: block;
            margin: 0px auto;
            border-radius: 50%;
            padding: 5px;
            border: 1px solid #e5e5e5;
            cursor: pointer;
        }
        #globalMessageBody > .form-group {
            margin-top: 0.5rem;
        }
        #globalMessageBody > .form-group > label {
            line-height: 35px;
        }


    </style>
</head>
<body>
<div id="whole">
    <nav>
        <span class="title">信息收集系统</span>
        <div id="navs">

            <div th:each="permit : ${permitTree}" style="padding-left: 15px">
                <a th:class="'nav-item '+${permit.getUrl().equals('/manage/home')?'nav-active':''}"
                   th:href="'#'+${permit.getUrl()}">
                    <i th:class="'fa fa-'+${permit.getIcon()}" aria-hidden="true"/></i>
                    <span th:text="${permit.getName()}"></span>
                    <span class="messageCount" th:if="${permit.getMessageCount() > 0}"
                          th:text="${permit.getMessageCount()}"></span>
                </a>
                <div class="nav-item-box hidden"
                     th:if="${permit.getChildren() != null and permit.getChildren().size() > 0}">
                    <a class="nav-item" th:each="childrenPermit : ${permit.getChildren()}"
                       th:href="'#'+${childrenPermit.getUrl()}">
                        <i th:class="'fa fa-'+${childrenPermit.getIcon()}" aria-hidden="true"/></i>
                        <span th:text="${childrenPermit.getName()}"></span>
                        <span class="messageCount" th:if="${childrenPermit.getMessageCount() > 0}"
                              th:text="${childrenPermit.getMessageCount()}"
                              th:id="${childrenPermit.getName()==IN_PROGRESS?'in_progress':''}"></span>
                    </a>
                </div>
            </div>
        </div>
    </nav>
    <div id="right">
        <header>
            <div id="status-control">
                <img th:src="${type==0?'/img/users.png':'/img/collector.png'}" class="img-thumbnail avatar" >
                <span th:text="${nickname}" class="nickname"></span>
                <div class="dropdown-menu" id="my-dropdown-menu">
                    <a class="dropdown-item" href="#" id="profile">
                        <i class="fa fa-user-circle-o" aria-hidden="true"/></i>
                        个人信息
                    </a>
                    <a class="dropdown-item" href="#" id="alterPasswordButton">
                        <i class="fa fa-key"></i>
                        修改密码</a>
                    <div class="dropdown-divider"></div>
                    <a class="dropdown-item" href="/logout">
                        <i class="fa fa-sign-out" aria-hidden="true"/></i>
                        退出登录
                    </a>
                </div>
            </div>
        </header>
        <main>
            <iframe height="100%" width="100%" src="/manage/home"></iframe>
        </main>
    </div>
</div>
<!-- Modal -->
<div class="modal fade" id="globalModal" data-backdrop="static" data-keyboard="false" tabindex="-1"
     aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="globalMessageTitle"></h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="globalMessageBody">

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="globalMessageConfirm">确认</button>
            </div>
        </div>
    </div>
</div>

<script type="module">
    import {POST, GET, POST_FORM} from "/js/request.js";
    import { bootstrapModalController } from "/js/bootstrapModalController.js";

    // 获取 #status-control 和 .dropdown-menu 的 jQuery 对象
    const $statusControl = $('#status-control');
    const $dropdownMenu = $('div.dropdown-menu');

    // 当用户将鼠标移动到 #status-control 上时，显示 .dropdown-menu
    $statusControl.on('mouseover', function () {
        $dropdownMenu.show();
    });

    // 当用户将鼠标移开 #status-control 时，隐藏 .dropdown-menu
    $statusControl.on('mouseout', function () {
        $dropdownMenu.hide();
    });
    // 展开/收缩子项
    $(".nav-item").click(function (event) {
        let nav_item_box = $(this).siblings(".nav-item-box");
        if (nav_item_box.hasClass('hidden')) {
            nav_item_box.slideDown(200); // 设置动画执行时间为 300ms
        } else {
            nav_item_box.slideUp(200);
        }
        nav_item_box.toggleClass('hidden');
        if (nav_item_box == null || nav_item_box.length == 0) {
            $("#navs .nav-active").removeClass("nav-active")
            $(this).addClass("nav-active")
        } else {
            event.preventDefault();
        }

    })

    function getTab(url) {
        for (let view of $("main iframe")) {
            // 如果当前元素的 src 属性等于 /manage，则进行相应的操作
            if (view.src.endsWith(url)) {
                return view;
            }
        }
        return null;
    }

    // 全局消息函数
    window.Message = function (title, content, handle) {
        bootstrapModalController({modalBox:"#globalModal", modalTitle:"#globalMessageTitle", modalBody:"#globalMessageBody", modalConfirm:"#globalMessageConfirm",size:""},
            title, content, handle)
    }

    function addView(url) {
        let tab = getTab(url);
        if (tab != null) {
            return
        }
        // 创建新的 iframe 元素
        let newIframe = $('<iframe>').attr({
            src: url,
            width: '100%',
            height: '100%'
        });
        // 将新的 iframe 元素添加到 main 标签中
        $('main').append(newIframe);
        let iframeWindow = newIframe[0].contentWindow; // 获取每个 iframe 的 window 对象
        // 给子容器iframe挂载全局消息函数
        iframeWindow.Message = window.Message;
    }

    function switchTab(url) {
        let tab = getTab(url);
        if (tab == null) return null;
        $('main iframe').hide();
        $(tab).show();
    }

    // 监听 hashchange 事件
    $(window).on('hashchange', function () {
        let hash = window.location.hash;
        let url = hash.substring(1);
        addView(url);
        switchTab(url)
    });

    // 更新可提交数
    function updateSubmittableCount() {
        GET("/collect/getSubmittableCount").then(result => {
            if (result.success) {
                // 更新左侧的进行中-待提交数量
                $("#in_progress").text(result.data)
                if (result.data == 0) {
                    $("#in_progress").css("display", "none")
                } else {
                    $("#in_progress").css("display", "inline")
                }
                console.log("更新提可提交数量成功！")
            } else {
                console.log("更新提可提交数量失败！")
            }
        })
    }

    window.addEventListener('message', event => {
        console.log("父容器接收到了信息~~")
        if (event.data == "UPDATE_SUBMITTABLE_COUNT_EVENT") updateSubmittableCount();
    });
    window.addEventListener('message', event => {
        console.log("父容器接收到了信息,当前在子页面显示登录页面问题~~")
        if (event.data == "IN_LOGIN_PAGE_EVENT") window.location.reload("/login.html");
    });

    // 清理掉页面的hash
    function clearUrlHash() {
        // 获取当前 URL
        let currentUrl = window.location.href;
        // 清理 hash 部分
        let cleanUrl = currentUrl.split('#')[0];
        // 修改浏览器历史记录
        window.history.replaceState(null, null, cleanUrl);
    }

    // 清理掉哈希
    clearUrlHash()
    // 用户信息
    let userInfo = {avatar: ""}
    function refreshUserInfo() {
        // 获取用户信息
        GET("/getUserInfo").then(result => {
            if (result.success) {
                userInfo = result.data;
                // 刷新页面用户数据
                $("#status-control > .nickname").text(userInfo.nickname)
                if(userInfo.avatar != null && userInfo.avatar !== "") $("#status-control > .avatar").attr("src",userInfo.avatar);
            } else {
                alert("获取用户信息失败~")
            }
        })
    }
    refreshUserInfo();

    // 点击用户信息/修改
    $("#profile").click(async function () {
        // 获取用户信息
        await GET("/getUserInfo").then(result => {
            if (result.success) {
                userInfo = result.data;
            } else {
                alert("获取用户信息失败~")
            }
        })

        window.Message("用户信息", `
            <div class="form-group">
                <img src="${userInfo.avatar}" for="avatar" id="avatar-img" onerror="this.src='/img/default_avatar.png';" />
                <input type="file" hidden name="avatarFile" id="avatar"  >
            </div>
            <div class="form-group">
                <label for="nickname">姓名：</label>
                <input type="text" class="form-control" name="nickname" value="${userInfo.nickname}" id="nickname" placeholder="请输入您的昵称..." >
            </div>
            <div class="form-group" style="display: ${userInfo.studentId == null ? 'none' : 'block'}">
                <label for="student_id">学号（可便于快速填写收集）：</label>
                <input type="text" value="${userInfo.studentId}" class="form-control" name="student_id" id="student_id" placeholder="请输入您的学号..." >
            </div>
            <div class="form-group">
                <label>性别：</label>
                <div id="sex-radio-box">
                      <div class="custom-control custom-radio">
                        <input type="radio" class="custom-control-input" id="male" name="sex" value="1" ${userInfo.sex == 1 ? 'checked' : ''}  >
                        <label class="custom-control-label" for="male" >男</label>
                      </div>
                      <div class="custom-control custom-radio mb-3">
                        <input type="radio" class="custom-control-input" id="female" name="sex" value="-1" ${userInfo.sex == -1 ? 'checked' : ''} >
                        <label class="custom-control-label" for="female">女</label>
                      </div>
                </div>
            </div>
<!--            <div class="form-group">-->
<!--                <label for="birth">出生年月：</label>-->
<!--                <input type="date" class="form-control" name="birth" id="birth" >-->
<!--            </div>-->
        `, function (close, {avatarFile, nickname, student_id, sex}) {
            let formData = {nickname, studentId: student_id, sex};

            if (avatarFile != null && avatarFile.length != 0) formData.avatarFile = avatarFile[0];
            POST_FORM("/updateUserInfo", formData).then(result => {
                if (result.success) {
                    refreshUserInfo();
                    close();
                } else {
                    alert("更新信息失败！")
                }
            })

        });
    })

    $("#alterPasswordButton").click(function () {
        window.Message("修改登录密码", `
            <div class="form-group">
                <label for="chooseCollectFile">新密码：</label>
                <input type="password" class="form-control" name="newPassword" placeholder="请输入新的密码..." >
            </div>
            <div class="form-group">
                <label for="chooseCollectFile">确认新密码：</label>
                <input type="password" class="form-control" name="reNewPassword" placeholder="请再次输入新的密码..." >
            </div>
            <div class="form-group">
                <label for="chooseCollectFile">旧密码：</label>
                <input type="password" class="form-control" name="oldPassword" placeholder="请输入当前的密码..." >
            </div>
        `, function (close, {newPassword, reNewPassword, oldPassword}) {
            console.log(newPassword, reNewPassword, oldPassword)
            if (reNewPassword != newPassword) {
                alert("两次输入的密码不一致！");
                return;
            }
            POST("/alterPassword", {newPassword, oldPassword}).then(result => {
                if (result.success) {
                    alert("修改密码成功，下次登录生效！");
                    close()
                } else {
                    alert("修改密码失败！" + result.message)
                }
            })


        });
    })

    $("#globalModal").on("click", "#avatar-img", function () {
        console.log("点击了")
        $("input[name='avatarFile']").click().change(function (event) {
            let files = event.target.files;
            if (files == null || files.length == 0) return;
            let selectedFile = files[0]
            let reader = new FileReader();
            // 读取文件并将其转换为数据URL
            reader.onload = function (event) {
                let dataURL = event.target.result;
                // 将数据URL赋值给<img>标签的src属性
                $("#avatar-img").attr("src", dataURL);
            };
            reader.readAsDataURL(selectedFile);
        })
    })


</script>
</body>
</html>